<?php
namespace app\api\controller\service;

use app\common\controller\Api;
use fast\Random;
use think\Db;


/**
 * 首页接口
 */
class Recharge extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 用户充值余额
     * @return void
     */
    public function recharge()
    {
        $uid = $this->auth->id;
        $money = model('app\api\model\service\User')->where('id',$uid)->value('money');
        $type = input('type','');
        if($type == 'recharge')
        {
            $price = sprintf("%.2f",input('price',''));
            $price <=0 && $this->error('充值金额错误');
            $orderId = 'Recharge'.Random::alnum(5).'-'.$uid.'-'.time();
            $paytype = input('paytype/d',0);
            $re = '';
            Db::startTrans();
            try{
                $recharge = new \app\api\model\service\Recharge(['user_id'=>$uid,'price'=>$price,'orderId'=>$orderId,'paytype'=>$paytype]);
                $recharge->allowField(true)->save();
                $re = \addons\service\library\Pay::payOrder(['amount'=>$price,'orderid'=>$orderId,'title'=>'充值余额'],$paytype,$uid,0);
                Db::commit();

            } catch (Exception $e) {
                Db::rollback();
                $this->error('支付拉起失败',$e->getMessage());
            }
            $this->success('支付信息返回成功',$re);
        }
        $this->success('信息返回成功',$money);
    }


    /**
     * 充值记录列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function list()
    {
        $uid = $this->auth->id;
        $page = input('page/d',1);
        $list = model('app\api\model\service\Recharge')
            ->where(['user_id'=>$uid,'state'=>1])
            ->field('id,price,orderId,paytype,createtime')
            ->order('id desc')
            ->page($page)
            ->limit(10)
            ->select();
        $this->success('信息返回成功',$list);
    }


}
